package com.feri.rbacsys.service.impl;

import com.feri.rbacsys.config.SystemConfig;
import com.feri.rbacsys.dao.OssDao;
import com.feri.rbacsys.entity.Oss;
import com.feri.rbacsys.service.intf.OssService;
import com.feri.rbacsys.util.AliOssUtil;
import com.feri.rbacsys.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @description: 业务接口实现层
 */
@Service
public class OssServiceImpl implements OssService {
    /**
    *注入持久层对象*/
    @Resource
    private OssDao dao;

    /**
    * 新增内容*/
    @Override
    public R save(Oss oss) {
        if(oss !=null){
            int i=dao.insert(oss);
            if(i>0){
                return R.ok();
            }
        }
        return R.fail("亲，新增异常！");
    }
    /**
    * 修改内容*/
    @Override
    public R update(Oss oss) {
        if(oss !=null){
            int i=dao.updateById(oss);
            if(i>0){
                return R.ok();
            }
        }
        return R.fail("亲，修改异常！");
    }
    /**
    *删除 */
    @Override
    public R del(long id){
        if(id>0){
            int i=dao.deleteById(id);
            if(i>0){
                return R.ok();
            }
        }
        return R.fail("删除异常");
    }

    /**
    * 查询详情*/
    @Override
    public R queryById(long id){
        return R.ok(dao.selectById(id));
    }

    /**
    * 查询 所有数据*/
    @Override
    public R queryAll() {
        return R.ok(dao.selectList(null));
    }

    @Override
    public R uploadImg(MultipartFile file) {
       return upload(file, SystemConfig.OSS_IMG);
    }

    private R upload(MultipartFile file,int type){
        //1.验证
        if(!file.isEmpty()){
            //2.获取名称 唯一
            String name=rename(file.getOriginalFilename());
            //3.上传阿里云的oss 获取访问地址
            try {
                AliOssUtil.upload(name,file.getBytes());

                Date edate=getEdate(10);
                String url=AliOssUtil.getPath(name,edate);
                //4.存储到数据库
                dao.insert(new Oss(AliOssUtil.BUCKETNAME,name,url,type,edate));

                //返回
                return R.ok(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail();
    }

    private String rename(String name){
        if(name.length()>30){
            name=name.substring(name.length()-30);
        }
        return System.currentTimeMillis()+"_"+new Random().nextInt(20) +"_"+name;
    }
    private Date getEdate(int year){
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.YEAR,year);
        return calendar.getTime();
    }
}
